package 力扣._105_从前序与中序遍历序列构造二叉树;

import 力扣.公用数据结构.TreeNode;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {

    int now = 0;

    public TreeNode build(int[] preorder, int[] inorder, int l, int r) {
        if (l > r)
            return null;
        // 找到当前子树根节点
        for (int i = l; i <= r; i++) {
            if (preorder[now] == inorder[i]) {
                now++;
                TreeNode root = new TreeNode(inorder[i]);
                root.left = build(preorder, inorder, l, i - 1);
                root.right = build(preorder, inorder, i + 1, r);

                return root;
            }
        }
        return null;
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        TreeNode node = build(preorder, inorder, 0, preorder.length - 1);
        return node;
    }

    public static void main(String[] args) {
        int[] preorder = new int[]{3, 9, 20, 15, 7};
        int[] inorder = new int[]{9, 3, 15, 20, 7};
        TreeNode treeNode = new Solution().buildTree(preorder, inorder);
    }
}